<?php
/**
 * TinyCatPHP 极简、快速、创新、易用、高性能的PHP应用开发框架
 * User: CnTaiGe <hst042@163.com>
 * Date: 2017/11/19
 */

namespace TinyCatPHP\libs\handler;

use TinyCatPHP\exception\SysException;
use TinyCatPHP\libs\config\Config;

class Interceptor
{
    protected $_intercept;
    protected static $_instance = null;

    private function __construct()
    {
        $this->_intercept = Config::load('intercept');
    }

    /**
     * @return Interceptor
     */
    public static function instance()
    {
        if (self::$_instance === null)
            self::$_instance = new self();
        return self::$_instance;
    }

    /**
     * 开始创建控制器
     */
    public function createAction()
    {
        $this->runIntercept('create_action');
    }

    /**
     * 开始运行具体的控制器方法
     */
    public function runAction()
    {
        $this->runIntercept('run_action');
    }

    /**
     * 控制器执行完成
     */
    public function endAction()
    {
        $this->runIntercept('end_action');
    }

    protected function runIntercept($it)
    {
        if (isset($this->_intercept[$it])) {
            if (is_array($this->_intercept[$it])) {
                if (method_exists($this->_intercept[$it][0], $this->_intercept[$it][1])) {
                    call_user_func($this->_intercept[$it]);
                } else {
                    throw new SysException('找不到方法 ' . implode('::', $this->_intercept['run_action']));
                }
            } elseif (is_callable($this->_intercept[$it])) {
                $this->_intercept[$it]();
            }
        }
    }

    /**
     * 应用初始化完成
     */
    public function initApp()
    {
        $this->runIntercept('init_app');
    }

    /**
     * 应用执行完成
     */
    public function endApp()
    {
        $this->runIntercept('end_app');
    }
}